package com.yunquan.ohana.ui.calendar.event.month.adapter

import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.yunquan.ohana.databinding.ItemEventMonthBaseBinding
import com.yunquan.ohana.ui.calendar.event.month.EventMonthItemViewModel
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter

class EventMonthBaseAdapter(
    val width: Int,
    val height: Int,
) : BindingRecyclerViewAdapter<EventMonthItemViewModel>() {

    override fun onBindBinding(binding: ViewDataBinding, variableId: Int, layoutRes: Int, position: Int, item: EventMonthItemViewModel?) {
        super.onBindBinding(binding, variableId, layoutRes, position, item)
        if (binding is ItemEventMonthBaseBinding) {
            val layoutParams = binding.clMonthRoot.layoutParams as ViewGroup.MarginLayoutParams
            layoutParams.width = width
            layoutParams.height = height
            binding.clMonthRoot.layoutParams = layoutParams

            // 优化交互：rv_event 保留滚动，但点击（单击）不需要分发到子项，统一触发父区域点击逻辑
            // 使用 GestureDetector 捕获单击手势，在不影响滚动的情况下执行 item 的 onItemClick
            val rv = binding.rvEvent
            val installed = rv.getTag(com.yunquan.ohana.R.id.tag_month_rv_click_installed) as? Boolean ?: false
            if (!installed) {
                val detector = GestureDetector(rv.context, object : GestureDetector.SimpleOnGestureListener() {
                    override fun onSingleTapUp(e: MotionEvent): Boolean {
                        item?.onItemClick?.execute()
                        return true
                    }
                })

                rv.addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
                    override fun onInterceptTouchEvent(recyclerView: RecyclerView, e: MotionEvent): Boolean {
                        // 返回 true 仅在识别为单击时，保持滚动事件由 RecyclerView 自行处理
                        return detector.onTouchEvent(e)
                    }
                })
                rv.setTag(com.yunquan.ohana.R.id.tag_month_rv_click_installed, true)
            }
        }
    }
}